import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from "@/router/routes";
import store from '@/store'
import {Notification} from "element-ui";

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
const whitePath = ["/login"];
router.beforeEach(((to, from, next) => {
    if (localStorage.getItem('authorization')) {
        /* has token*/
        if (to.path === '/login') {
            Notification({
                message: '您已登录，请勿重复登录!',
                type: "warning"
            })
            next({path: '/'})
        } else {
            if (store.state.name === undefined || store.state.name === '') {
                store.dispatch("GetInfo").then(() => {

                });
                next();
            }
        }
    } else {
        // 没有token
        if (whitePath.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            Notification({
                message: '您未登录，请登录!',
                type: "warning"
            })
            next(`/login`)
        }
    }
}))

export default router
